#include <jni.h>
#include <string>
#include "mdfu.h"
#include <vector>
#include "upgrade.h"

extern "C"
JNIEXPORT jstring JNICALL
Java_com_oem_upgrade_UpgradeAPI_testJni(JNIEnv *env, jobject /* this */) {
    std::string result = Mdfu::testJni();
    return env->NewStringUTF(result.c_str());
}

extern "C"
JNIEXPORT jstring JNICALL
Java_com_oem_upgrade_UpgradeAPI_testFrameData(JNIEnv *env, jobject /* this */) {
    std::string result = Mdfu::testFrameData();
    return env->NewStringUTF(result.c_str());
}

extern "C"
JNIEXPORT jobjectArray JNICALL
Java_com_oem_upgrade_UpgradeAPI_getUpgradeChunks(JNIEnv *env, jobject /* this */) {
    // 創建 upgrade 對象
    upgrade upg;

    // 調用 UPGRADE_CHUNKS 獲取數據
    std::vector<std::vector<uint8_t>> chunks = upg.UPGRADE_CHUNKS();

    // 獲取 Java byte[] 類型
    jclass byteArrayClass = env->FindClass("[B");
    if (byteArrayClass == nullptr) {
        return nullptr; // 如果找不到類型，直接返回 null
    }

    // 創建 jobjectArray 來存儲多個 byte[]
    jobjectArray chunkArray = env->NewObjectArray(chunks.size(), byteArrayClass, nullptr);

    for (size_t i = 0; i < chunks.size(); i++) {
        // 創建每個 byte[] 並填充數據
        jbyteArray byteArray = env->NewByteArray(chunks[i].size());
        env->SetByteArrayRegion(byteArray, 0, chunks[i].size(), reinterpret_cast<const jbyte*>(chunks[i].data()));

        // 將 byte[] 添加到 jobjectArray 中
        env->SetObjectArrayElement(chunkArray, i, byteArray);

        // 釋放局部引用
        env->DeleteLocalRef(byteArray);
    }

    return chunkArray;
}